package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        //1.判断登陆时用户名和密码填写是否为空
        if (vo == null || Strings.isNullOrEmpty(vo.getUsername()) ||
                Strings.isNullOrEmpty(vo.getPassword())) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //2.根据用户名查询用户信息，判断用户名是否存在
        SysUser user = sysUserMapper.findUserByUserName(vo.getUsername());
        if (user == null) {
            return R.error(ResponseCode.ACCOUNT_EXISTS_ERROR.getMessage());
        }
        //3.判断查询的数据库中的密码和输入的密码进行校验
        boolean flag = passwordEncoder.matches(vo.getPassword(),user.getPassword());
        if (!flag) {
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //登陆成功，响应数据
        LoginRespVo respVo = new LoginRespVo();
        //属性名称与类型必须相同，否则copy不到
        BeanUtils.copyProperties(user, respVo);
        return R.ok(respVo);
    }
}
